﻿<!DOCTYPE html>
<!--[if IE]><![endif]-->
<html>
  
  <head>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async="" src="https://www.googletagmanager.com/gtag/js?id=UA-39155502-5"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
  
      gtag('config', 'UA-39155502-5');
    </script>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Save an entity | MongoDB.Entities </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Save an entity | MongoDB.Entities ">
    <meta name="generator" content="docfx 2.56.5.0">
    <meta name="description" content="A data access library for MongoDB with an elegant api, LINQ support and built-in entity relationship management.">
    <link rel="shortcut icon" href="../images/favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">
    
    <meta property="docfx:rel" content="../">
    <meta property="docfx:newtab" content="true">
    <meta property="og:title" content="MongoDB.Entities">
    <meta property="og:site_name" content="MongoDB.Entities">
    <meta property="og:url" content="https://mongodb-entities.com">
    <meta property="og:description" content="A data access library for MongoDB with an elegant api, LINQ support and built-in entity relationship management,">
    <meta property="og:type" content="website">
    <meta property="og:image" content="https://mongodb-entities.com/images/social-square.png">  
  </head>
  <body data-spy="scroll" data-target="#affix" data-offset="120">
    <div id="wrapper">
      <header>
        
        <nav id="autocollapse" class="navbar navbar-inverse ng-scope" role="navigation">
          <div class="container">
            <div class="navbar-header">
              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
              </button>
              
              <a class="navbar-brand" href="../index.html">
                <img id="logo" class="svg" src="../images/icon.png" alt="">
              </a>
            </div>
            <div class="collapse navbar-collapse" id="navbar">
              <form class="navbar-form navbar-right" role="search" id="search">
                <div class="form-group">
                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">
                </div>
              </form>
            </div>
          </div>
        </nav>
        
        <div class="subnav navbar navbar-default">
          <div class="container hide-when-search" id="breadcrumb">
            <ul class="breadcrumb">
              <li></li>
            </ul>
          </div>
        </div>
      </header>
      <div class="container body-content">
        
        <div id="search-results">
          <div class="search-list">Search Results for <span></span></div>
          <div class="sr-items">
            <p><i class="glyphicon glyphicon-refresh index-loading"></i></p>
          </div>
          <ul id="pagination" data-first="First" data-prev="Previous" data-next="Next" data-last="Last"></ul>
        </div>
      </div>
      <div role="main" class="container body-content hide-when-search">
        
        <div class="sidenav hide-when-search">
          <a class="btn toc-toggle collapse" data-toggle="collapse" href="#sidetoggle" aria-expanded="false" aria-controls="sidetoggle">Show / Hide Table of Contents</a>
          <div class="sidetoggle collapse" id="sidetoggle">
            <div id="sidetoc"></div>
          </div>
        </div>
        <div class="article row grid-right">
          <div class="col-md-10">
            <article class="content wrap" id="_content" data-uid="">
<h1 id="save-an-entity">Save an entity</h1>

<p>call <code>SaveAsync()</code> on any entity to persist it to the database.</p>
<pre><code class="lang-csharp">var book = new Book { Title = &quot;The Power Of Now&quot; }; 
await book.SaveAsync();
</code></pre>
<p>new entities are automatically assigned an <code>ID</code> when saved. saving an entity that has the <code>ID</code> already populated will <em><a href="Schema-Changes.html">replace</a></em> the matching entity in the database if it exists. if an entity with that <code>ID</code> does not exist in the database, a new one will be created. aka upserted.</p>
<h1 id="save-multiple-entities">Save multiple entities</h1>
<p>multiple entities can be saved in a single bulk operation like so:</p>
<pre><code class="lang-csharp">var books = new[] {
    new Book{ Title = &quot;Book One&quot; },
    new Book{ Title = &quot;Book Two&quot; },
    new Book{ Title = &quot;Book Three&quot;}
    };

await books.SaveAsync();
</code></pre>
<h1 id="save-via-db-static-class">Save via DB static class</h1>
<p>you can also use the DB static class for saving entities like so:</p>
<pre><code class="lang-csharp">await DB.SaveAsync(book);
await DB.SaveAsync(books);
</code></pre>
<h1 id="save-entities-partially">Save entities partially</h1>
<p>the above-mentioned <code>SaveAsync</code> methods will replace the entire document in the database with the values from the entity. if the goal is to only save the values of a subset of the properties, you have two choices to make your life easier.</p>
<h3 id="save-only-a-few-specified-properties">Save only a few specified properties</h3>
<pre><code class="lang-csharp">await book.SaveOnlyAsync(x =&gt; new { x.Title, x.Price });
</code></pre>
<p>this will save <strong>only</strong> the Title and Price properties and exclude all other properties of the entity.</p>
<h3 id="save-all-others-except-for-the-specified-properties">Save all others except for the specified properties</h3>
<pre><code class="lang-csharp">await book.SaveExceptAsync(x =&gt; new { x.AuthorName })
</code></pre>
<p>this will save all other properties of the entity <strong>except</strong> the <code>AuthorName</code> property.</p>
<div class="NOTE">
<h5>Note</h5>
<p>you should only specify root level properties with the <strong>New</strong> expression. i.e. <strong>x =&gt; x.Author.Name</strong> is not valid.</p>
</div>
<div class="TIP">
<h5>Tip</h5>
<p>if the <code>ID</code> value of the entity being saved is <code>null</code>, a new document will be created in the database. if the <code>ID</code> has a value, then the matching document will be updated instead.</p>
</div>
<h1 id="partial-save-with-attributes">Partial save with attributes</h1>
<p>if you find specifying <code>New</code> expressions everywhere in your code as above tedious when needing to omit properties while saving an entity, you can use the <code>SavePreservingAsync()</code> method together with the use of an attribute.</p>
<p>simply decorate the properties you want to omit with the [<a class="xref" href="../api/MongoDB.Entities.PreserveAttribute.html">Preserve</a>] attribute and call <code>book.SavePreservingAsync()</code> without having to supply an expression everytime. whatever properties you have decorated with <code>[Preserve]</code> attribute, will not be updated. all other properties of the entity will be updated with the values from your entity.</p>
<p>you can also do the opposite with the use of [<a class="xref" href="../api/MongoDB.Entities.DontPreserveAttribute.html">DontPreserve</a>] attribute. if you decorate properties with <code>[DontPreserve]</code>, only the values of those properties are written to the database and all other properties are implicitly ignored when calling <code>SavePreservingAsync()</code>.</p>
<div class="NOTE">
<h5>Note</h5>
<p>both <strong>[DontPreserve]</strong> and <strong>[Preserve]</strong> cannot be used together on the same entity type due to the conflicting nature of what they do.</p>
</div>
<h1 id="embed-an-entity">Embed an entity</h1>
<p>to store an unlinked copy of an entity,  call the <code>ToDocument()</code> method. doing so will store an independant duplicate (with a new ID) of the original entity that has no relationship to the original entity.</p>
<pre><code class="lang-csharp">book.Author = author.ToDocument();
book.OtherAuthors = (new Author[] { author2, author3 }).ToDocuments();
await book.SaveAsync();
</code></pre>
</article>
          </div>
          
          <div class="hidden-sm col-md-2" role="complementary">
            <div class="sideaffix">
              <div class="contribution">
                <ul class="nav">
                </ul>
              </div>
              <nav class="bs-docs-sidebar hidden-print hidden-xs hidden-sm affix" id="affix">
                <h5>In This Article</h5>
                <div></div>
              </nav>
            </div>
          </div>
        </div>
      </div>
      
      <footer>
        <div class="grad-bottom"></div>
        <div class="footer">
          <div class="container">
            <span class="pull-right">
              <a href="#top">Back to top</a>
            </span>
            Developed by <a href='https://github.com/dj-nitehawk'>Đĵ ΝιΓΞΗΛψΚ</a> / Licensed under <a href='https://github.com/dj-nitehawk/MongoDB.Entities/blob/master/LICENSE'>MIT</a> / Website generated by <a href='https://dotnet.github.io/docfx/'>DocFX</a>
            
          </div>
        </div>
      </footer>
    </div>
    
    <script type="text/javascript" src="../styles/docfx.vendor.js"></script>
    <script type="text/javascript" src="../styles/docfx.js"></script>
    <script type="text/javascript" src="../styles/main.js"></script>
  </body>
</html>
